package cn.com.surker.system.service.impl;

import cn.com.surker.enums.StateEnum;
import cn.com.surker.system.dao.*;
import cn.com.surker.system.entity.SysOrgPosition;
import cn.com.surker.system.entity.SysOrigin;
import cn.com.surker.system.entity.SysPosition;
import cn.com.surker.system.entity.SysUser;
import cn.com.surker.system.service.OriginPositionService;
import cn.com.surker.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.snaker.engine.SnakerException;
import org.snaker.engine.entity.Order;
import org.snaker.engine.entity.Task;
import org.snaker.engine.helper.JsonHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Author lucky
 * @create 2022年10月17 19:38
 * @desc 流程用户选择器工具类
 */
@Slf4j
@Service("orgPosService")
public class OriginPositionServiceImpl implements OriginPositionService {

    @Resource
    private SysUserDao userDao;//用户dao
    @Resource
    private SysPositionDao positionDao;//岗位dao
    @Resource
    private SysOrgPositionDao orgPositionDao;//部门岗位dao
	@Resource
	private SysOriginDao originDao;		// 组织机构
    @Resource
    private SysPositionDao sysPositionDao;//岗位dao
    @Resource
    private SysRoleDao roleDao;//角色dao
    @Resource
    private DataSourceInfoDao dataSourceInfoDao;
    @Resource
    private SysUserPositionDao userPositionDao;


    /**
     * 查询部门下所有用户
     * @param deptId
     * @return
     */
    public List<String> getDeptAllUser(String deptId) {
        if (StringUtils.isNull(deptId))
            throw new SnakerException("操作失败，绑定的部门不能为空！");

        List<Map<String, Object>> userList = positionDao.queryDeptAllUser(deptId);
        if (userList == null || userList.size() == 0)
            throw new SnakerException("操作失败，上级岗位的用户不存在！");

        List<String> resultList = new ArrayList<>();
        for (int i = 0; i < userList.size(); i++) {
            resultList.add(StringUtils.convertString(userList.get(i).get("username")));
        }
        return resultList;
    }

    @Override
    public List<String> getGroupUser(String ids, String creator, String lastUpdator, String assigneeConfig, Long orgId, Long deptId, Long pid, Long parentPid, Map<String, Object> map, Order order, Task task) throws SnakerException {
        return null;
    }

    @Override
	public Integer saveInitOrgPos(SysOrgPosition orgPosition) {
    	if(orgPosition == null){
    		return -1;
		}
		orgPosition.setStatus(StateEnum.ENABLED.getCode());
    	orgPosition.setCreateTime(new Date());
		int insert = orgPositionDao.insert(orgPosition);
		return insert;
	}

	@Override
	public Integer deleteOrgPos(Long id) {
    	if(id == null){
    		return -1;
		}
		SysOrgPosition orgPosition = new SysOrgPosition();
    	orgPosition.setId(id);
    	orgPosition.setStatus(StateEnum.DISABLED.getCode());
		int i = orgPositionDao.updateById(orgPosition);
		return i;
	}

	@Override
	public SysOrgPosition queryOrgPos(Long orgId, Long posId) {
    	QueryWrapper<SysOrgPosition> qw = new QueryWrapper<>();
    	qw.eq("status",StateEnum.ENABLED.getCode());
    	if(orgId != null){
    		qw.eq("org_id",orgId);
		}
    	if(posId != null){
    		qw.eq("pid",posId);
		}
		SysOrgPosition orgPosition = orgPositionDao.selectOne(qw);
		return orgPosition;
	}

	@Override
	public Integer updateOrgPosById(SysOrgPosition orgPosition) {
    	if(orgPosition == null){
    		return -1;
		}
    	if(orgPosition.getId() == null){
    		return -1;
		}
		int i = orgPositionDao.updateById(orgPosition);
		return i;
	}

	@Override
	public List<Map<String,Object>> queryPositionByOrg(Long orgId) {
    	if(orgId == null){
    		return new ArrayList<>();
		}
    	// 查询关联数据
		UpdateWrapper<SysOrgPosition> uw = new UpdateWrapper<>();
    	uw.eq("status",StateEnum.ENABLED.getCode());
    	if(orgId != null){
			uw.eq("org_id",orgId);
		}
    	uw.orderByDesc("is_boss","create_time");
		List<SysOrgPosition> orgPositions = orgPositionDao.selectList(uw);
		if(orgPositions == null){
			return new ArrayList<>();
		}
		List<Map<String,Object>> resList = new ArrayList<>();
		for(SysOrgPosition orgPosition : orgPositions){
			// 部门id
			Long deptId = orgPosition.getOrgId();
			// 查询部门的上级部门列表（包含本部门，从小往大）
			SysOrigin sysOrigin = originDao.relationParentOrigin(deptId);
			List<Map<String,Object>> orgs = new ArrayList<>();
			relationParentOrg(orgs,sysOrigin);
			// 岗位id
			Long posId = orgPosition.getPid();
			// 查询岗位信息
			SysPosition position = positionDao.selectById(posId);
			// 上级岗位
			Long parentPid = orgPosition.getParentPid();
			SysPosition parentPos = positionDao.selectById(parentPid);
			Map<String,Object> res = new HashMap<>();
			// 设置关联信息
			res.put("orgPosition",orgPosition);
			// 设置岗位信息，上级岗位信息
			res.put("pos",position);
			res.put("parentPos",parentPos);
			// 设置部门列表
			res.put("orgs",orgs);
			resList.add(res);
		}
		return resList;
	}

	@Override
	public SysOrgPosition queryById(Long id) {
    	if(id == null){
    		return null;
		}
		SysOrgPosition orgPosition = orgPositionDao.selectById(id);
		return orgPosition;
	}

	@Override
	public List<SysOrgPosition> queryChildPosList(Long deptId, Long parentPosId) {
    	if(deptId == null || parentPosId == null){
    		return null;
		}
    	QueryWrapper<SysOrgPosition> qw = new QueryWrapper<>();
    	qw.eq("status",StateEnum.ENABLED.getCode());
    	qw.eq("org_id",deptId);
    	qw.eq("parent_pid",parentPosId);
		List<SysOrgPosition> orgPositions = orgPositionDao.selectList(qw);
		return orgPositions;
	}


    /**
     * 查询用户管理岗位
     * @param uid
     * @return
     */
    public List<Map<String, Object>> findDefaultPosition(Long uid, Boolean isAll) {
        if (isAll) {
            List<Map<String, Object>> list = orgPositionDao.findByUserOrgAll();
            if (list == null || list.size() == 0)
                return null;
            return list;
        } else {
            if (StringUtils.isNull(uid))
                return null;
            List<Map<String, Object>> list = orgPositionDao.findByUserOrg(uid);
            if (list == null || list.size() == 0)
                return null;
            return list;
        }
    }

    /**
     * 查询集团下属所有用户
     * @return
     */
    public List<String> getGroupUser() {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 0);
        List<SysUser> userList = userDao.selectList(queryWrapper);
        if (userList == null || userList.size() == 0)
            throw new SnakerException("未获取启用用户，请联系管理员！");

        List<String> resultList = new ArrayList<>();
        for (int i = 0; i < userList.size(); i++) {
            resultList.add(userList.get(i).getUsername());
        }
        return resultList;
    }


    /**
     * 查询所属岗位下面所有用户
     * @param ids 岗位ID
     * @return
     */
    private List<String> getPositionUser(String ids) {
        if (StringUtils.isNull(ids))
            return null;

        List<Map<String, Object>> list = positionDao.queryPositionUser(ids);
        if (list == null || list.size() == 0)
            return null;

        List<String> result = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            result.add(StringUtils.convertString(list.get(i).get("username")));
        }
        return result;
    }


    /**
     * 获取启动人 上一级审批同一工厂用户
     * @param creator 创建人或上次流程执行人
     * @param ids 岗位ID
     * @param orgId 工厂ID
     * @param deptId 部门ID
     * @param pid 岗位ID
     * @param nType 运行类型
     * @return
     */
    public List<String> getSameFacUser(String creator,String ids,Long orgId, Long deptId, Long pid, Integer nType) {
        List<String> resultList = new ArrayList<>();
        if (StringUtils.isNull(orgId)) {
            throw new SnakerException("该流程绑定的工厂为空，请联系管理员！");
        }
        if (StringUtils.isNull(nType) || nType == 0) {
            if (ids == null || ids.trim().equals("")) {
                QueryWrapper<SysOrgPosition> orgPostQuery = new QueryWrapper<>();
                orgPostQuery.eq("pid", pid);
                orgPostQuery.eq("org_id", deptId);
                orgPostQuery.eq("is_boss", 1);
                orgPostQuery.eq("status", 0);
                List<SysOrgPosition> orgList = orgPositionDao.selectList(orgPostQuery);
                if (orgList != null && orgList.size() > 0 && orgList.get(0).getParentPid() != 4
                        && orgList.get(0).getParentPid() != 199 && orgList.get(0).getParentPid() != 120
                        && orgList.get(0).getParentPid() != 60 && orgList.get(0).getParentPid() != 45) {
                    //父级岗位不等于总经理、副总经理、集团总经理、董事长
                    ids = orgList.get(0).getParentPid() + "";
                } else {
                    orgPostQuery = new QueryWrapper<>();
                    orgPostQuery.eq("org_id", deptId);
                    orgPostQuery.eq("status", 0);

                    orgPostQuery.inSql("pid", "select parent_pid from sys_org_position where org_id = "
                            + deptId + " and status = 0 and pid = " + pid);
                    orgList = orgPositionDao.selectList(orgPostQuery);
                    if (orgList != null && orgList.size() > 0)
                        ids = orgList.get(0).getParentPid() + "";
                    else {/**查询是否有N+4岗位存在**/
                        orgPostQuery.eq("org_id", deptId);
                        orgPostQuery.eq("status", 0);
                        orgPostQuery.inSql("pid", "select parent_pid from sys_org_position where org_id = "
                                + deptId + " and status = 0 and pid in (select parent_pid from sys_org_position where org_id = "
                                + deptId + " and status = 0 and pid = " + pid + ")");
                        orgList = orgPositionDao.selectList(orgPostQuery);
                        if (orgList != null && orgList.size() > 0)
                            ids = orgList.get(0).getParentPid() + "";
                        else {
                            orgPostQuery = new QueryWrapper<>();
                            orgPostQuery.eq("pid", pid);
                            orgPostQuery.eq("org_id", deptId);
                            orgPostQuery.eq("status", 0);
                            orgList = orgPositionDao.selectList(orgPostQuery);
                            if (orgList != null && orgList.size() > 0)
                                ids = orgList.get(0).getParentPid() + "";
                        }
                    }
                }
            }
        } else if (nType == 1) {//N+3
            QueryWrapper<SysOrgPosition> orgPostQuery = new QueryWrapper<>();
            orgPostQuery.eq("org_id", deptId);
            orgPostQuery.eq("status", 0);
            orgPostQuery.inSql("pid", "select parent_pid from sys_org_position where org_id = "
                    + deptId + " and status = 0 and pid in (select parent_pid from sys_org_position where org_id = "
                    + deptId + " and status = 0 and pid = " + pid + ")");
            List<SysOrgPosition> orgList = orgPositionDao.selectList(orgPostQuery);
            if (orgList != null && orgList.size() > 0) {
                if (orgList.get(0).getPid().longValue() == 4L)//如果是总经理
                    ids = orgList.get(0).getPid() + "";
                else
                    ids = orgList.get(0).getParentPid() + "";
            } else {
                QueryWrapper<SysOrgPosition> orgQuery = new QueryWrapper<>();
                orgQuery.eq("status", 0);
                orgQuery.inSql("pid", "select parent_pid from sys_org_position where org_id = "
                        + deptId + " and status = 0 and pid = " + pid);
                orgQuery.eq("org_id", deptId);

                List<SysOrgPosition> orgList1 = orgPositionDao.selectList(orgQuery);
                if (orgList1 != null && orgList1.size() > 0) {
                    SysOrgPosition orgPosition1 = orgList1.get(0);
                    if (orgPosition1.getPid() == 4 || orgPosition1.getParentPid() == 4)
                        ids = orgList1.get(0).getParentPid() + "";
                }
            }
        } else if (nType == 2) {
            /**查询是否有N+4岗位存在**/
            QueryWrapper<SysOrgPosition> orgPostQuery = new QueryWrapper<>();
            orgPostQuery.eq("org_id", deptId);
            orgPostQuery.eq("status", 0);
            orgPostQuery.inSql("pid", "select parent_pid from sys_org_position where org_id = "
                    + deptId + " and status = 0 and pid in (select parent_pid from sys_org_position where org_id = "
                    + deptId + " and status = 0 and pid in (select parent_pid from sys_org_position where org_id = "
                    + deptId + " and status = 0 and pid = " + pid + "))");
            List<SysOrgPosition> orgList = orgPositionDao.selectList(orgPostQuery);
            if (orgList != null && orgList.size() > 0)
                ids = orgList.get(0).getParentPid() + "";
            else {
                orgPostQuery = new QueryWrapper<>();
                orgPostQuery.eq("org_id", deptId);
                orgPostQuery.eq("status", 0);
                orgPostQuery.eq("pid", pid);
                orgList = orgPositionDao.selectList(orgPostQuery);
                if (orgList != null && orgList.size() > 0)
                    ids = orgList.get(0).getParentPid() + "";
            }
        }

        List<Map<String, Object>> orgList = positionDao.queryOriginOrPosition(ids, orgId);
        for (Map<String, Object> map : orgList) {
            Long id = StringUtils.convertLong(map.get("id"));
            Long orgId_ = StringUtils.convertLong(map.get("parentId"));
            //如果是同一工厂
            Long positionId = StringUtils.convertLong(map.get("positionId"));
            List<Map<String, Object>> userList = positionDao.queryPositionOrOriginByUser(positionId, id, orgId_);//根据岗位、部门、工厂查询用户信息
            if (userList != null && userList.size() > 0) {
                for (int i = 0; i < userList.size(); i++) {
                    String username = StringUtils.convertString(userList.get(i).get("username"));
                    if (resultList.contains(username))
                        continue;
                    resultList.add(username);
                }
            }
        }

        return resultList;
    }


    /**
     * 同部门的负责人
     * @param deptId
     * @return
     */
    public List<String> getSameDeptUser(Long deptId){
        if(StringUtils.isNull(deptId)){
            throw new SnakerException("该流程绑定的部门为空，请联系管理员！");
        }

        List<Map<String, Object>> userList = positionDao.querySameDeptUser(deptId);
        List<String> resultList = new ArrayList<>();
        if (userList == null || userList.size() == 0)
            throw new SnakerException("该流程绑定的部门为空，请联系管理员！");

        for (int i = 0; i < userList.size(); i++) {
            resultList.add(StringUtils.convertString(userList.get(i).get("username")));
        }
        return resultList;
    }

	/**
	 * 迭代设置机构返回信息
	 * @param orgs
	 * @param origin
	 */
	private void relationParentOrg(List<Map<String,Object>> orgs, SysOrigin origin) {
		if(origin != null){
			Map<String,Object> org = new HashMap<>();
			Long id = origin.getId();
			String originName = origin.getOriginName();
			org.put("orgId",id);
			org.put("orgName",originName);
			orgs.add(org);
			SysOrigin parent = origin.getParent();
			relationParentOrg(orgs,parent);
		}
	}

}
